package self.cloud.domain.network;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import self.cloud.domain.network.entity.AddressType;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

@Service
public class NetworkBusiness {
    private static final Logger logger = LoggerFactory.getLogger(NetworkBusiness.class);

    @Autowired
    NetworkService networkService;

    public String getHostAddress(String networkName, AddressType addressType) throws SocketException {
        logger.debug("method getHostAddress [network.name]:{} [addressType]:{}", networkName, addressType);

        NetworkInterface network = null;

        if (networkName != null && !networkName.equals("")) {
            logger.debug("name is not null, try to find [{}]", networkName);
            network = this.networkService.findByName(networkName);
        }

        if (network == null) {
            throw new SocketException("Network Not Found");
        }

        InetAddress address = null;

        if(addressType == AddressType.IPV4) {
            address = this.networkService.findByIPv4(network);
        }

        if(addressType == AddressType.IPV6) {
            address = this.networkService.findByIPv6(network);
        }

        if (address == null) {
            throw new SocketException("InetAddress Not Found");
        }

        return address.getHostAddress();
    }

    public String findAllToString() throws SocketException {
        return this.networkService.findAllToString();
    }
}
